package com.teamin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.core.util.StringUtils;
import com.teamin.config.ErrorCode;
import com.teamin.entity.ActiveUser;
import com.teamin.entity.UserEntity;
import com.teamin.entity.WxUserEntity;
import com.teamin.mapper.UserMapper;
import com.teamin.mapper.WxUserMapper;
import com.teamin.service.IActiveUserService;
import com.teamin.service.UserService;
import com.teamin.service.WxService;
import com.teamin.web.exception.GlobalErrorInfoException;
import com.teamin.web.model.ErrorInfo;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class UserServiceImpl implements UserService {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
    @Value("${pcwx.appid}")
    private String APP_ID ;
    @Value("${pcwx.secret}")
    private String SECRET ;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private WxUserMapper wxUserMapper;
	@Autowired
	private WxService wxService;

	@Autowired
	private IActiveUserService activeUserService;

	@Override
	public int deleteUser(Long id) {
		return userMapper.deleteByPrimaryKey(id);
	}

	@Override
	public UserEntity wxPcLogin(String code,  String state) throws GlobalErrorInfoException {

		try {
			if (state.equals("4096")) {
				OkHttpClient okHttpClient = new OkHttpClient();
				//查询unionid
				Request request = new Request.Builder().url("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID
						+ "&secret=" + SECRET + "&code=" + code + "&grant_type=authorization_code").build();
				Call call = okHttpClient.newCall(request);
				Response response = call.execute();
				JSONObject jsonObject = JSON.parseObject(response.body().string());

				if(jsonObject.containsKey("unionid") && !StringUtils.isNullOrEmpty(jsonObject.getString("unionid"))) {
					//查询用户信息
					request = new Request.Builder().url("https://api.weixin.qq.com/sns/userinfo?access_token=" + jsonObject.getString("access_token")
					+ "&openid=" + jsonObject.getString("openid")).build();
					call = okHttpClient.newCall(request);
					response = call.execute();
					jsonObject = JSON.parseObject(response.body().string());
					WxUserEntity wxUserEntity = new WxUserEntity();
					wxUserEntity.setAvatarUrl(jsonObject.getString("headimgurl"));
					wxUserEntity.setMpOpenId(jsonObject.getString("openid"));
					wxUserEntity.setNickName(jsonObject.getString("nickname"));
					wxUserEntity.setUnionId(jsonObject.getString("unionid"));

					UserEntity us = saveOrUpdateWxUser(wxUserEntity);
					//更新用户有登录时间
					updateLoginTime(us.getUserId()) ;
					return us ;
				}else {
					//没有得到用户unionid
					throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.AUTH_CODE_FAIL));
				}
			} else {
				//state错误
				throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.STATE_CODE_FAIL));
			}
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
			//未知错误
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.UNKNOWN_ERROR.value(),e.getMessage()));
		}
	}
	
	/**
	 * 微信登陆
	 */
	public UserEntity wxLogin(WxUserEntity wxUserEntity) throws GlobalErrorInfoException {
		logger.info("wxLogin = "+wxUserEntity.toString());
		try {

			UserEntity us = saveOrUpdateWxUser(wxUserEntity);
			updateLoginTime(us.getUserId()) ;
			return us ;
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.WX_LOGIN_FAIL.value(),e.getMessage()));
		}
	}

	/**
	 * 新增用户到小程序中 ,
	 * @param record 用户信息
	 * @return long 用户ID
	 * @throws GlobalErrorInfoException
	 */
	@Override
	public long addUser(UserEntity record) throws GlobalErrorInfoException {
		try {
			int result = userMapper.insertSelective(record);
			if (result == 0) {
				throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.NOT_FOUND, ErrorCode.ADD_USER_FAIL));
			}
			return record.getUserId();
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.ADD_USER_FAIL));
		}

	}

	@Override
	public UserEntity selectUser(Long id) throws GlobalErrorInfoException {
		try {
			UserEntity userEntity = userMapper.selectByPrimaryKey(id);
			if (userEntity == null) {
				// 没有找到异常
				throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.NOT_FOUND, ErrorCode.FIND_USER_FAIL));
			}
			return userEntity;
		} catch (Exception e) {
			// 查询失败
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.FIND_USER_FAIL));
		}

	}

	@Override
	public long updateUser(UserEntity record) throws GlobalErrorInfoException {
		try {
			int result = userMapper.updateByPrimaryKeySelective(record);
			if (result == 0) {
				throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.NOT_FOUND, ErrorCode.UPDATE_USER_FAIL));
			}
			return record.getUserId();
		} catch (Exception e) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.UPDATE_USER_FAIL));
		}
	}

	/**
	 * 取消公众号的关注
	 * @param mpOpenId
	 * @return
	 */
	@Override
	public int cancleMPAttention(String mpOpenId) {
		return wxUserMapper.cancleMPAttention(mpOpenId) ;
	}

	/**
	 * 添加或更新微信用户 针对小程序
	 * @param wxUserEntity
	 * @return
	 * @throws GlobalErrorInfoException
	 */
	@Override
	public UserEntity saveOrUpdateWxUser(WxUserEntity wxUserEntity) throws GlobalErrorInfoException {
		WxUserEntity entity = wxUserMapper.selectWxUserEntity(wxUserEntity.getUnionId());
		// 新用户
		if (entity == null) {
			// 创建 WxUserEntity 新用户
			wxUserMapper.saveWxUserEntity(wxUserEntity);
			UserEntity userEntity = new UserEntity();
			userEntity.setHeadIcon(wxUserEntity.getAvatarUrl());
			userEntity.setUserName(wxUserEntity.getNickName());
			// 创建 UserEntity 新用户
			long userId = addUser(userEntity);
			wxUserEntity.setUserId(userId);
			// 关联用户
			wxUserMapper.updateWxUserEntity(wxUserEntity);

			//新增活跃用户记录
			ActiveUser activeUser = new ActiveUser();
			activeUser.setActiveUserId(userId);
			activeUser.setIsNew(0);
			this.activeUserService.save(activeUser);

			// 返回 UserEntity
			return selectUser(userId);

		}
		// 老用户
		else {

			//新增活跃用户记录
			ActiveUser activeUser = new ActiveUser();
			activeUser.setActiveUserId(entity.getUserId());

			Date loginTime = getLoginTime(entity.getUserId());
			if(loginTime == null){
				activeUser.setIsNew(0);
			}else{
				activeUser.setIsNew(1);
			}
			this.activeUserService.save(activeUser);

			wxUserEntity.setUserId(entity.getUserId());
			// 查询关联用户
			final UserEntity userEntity = userMapper.selectByPrimaryKey(wxUserEntity.getUserId());
			// 不存在关联用户
			if (userEntity == null) {
				UserEntity user = new UserEntity();
				user.setHeadIcon(wxUserEntity.getAvatarUrl());
				user.setUserName(wxUserEntity.getNickName());
				// 创建 UserEntity 新用户
				long userId = addUser(user);
				wxUserEntity.setUserId(userId);
				// 关联用户
				wxUserMapper.updateWxUserEntity(wxUserEntity);

				// 返回 UserEntity
				return selectUser(userId);
			}
			// 存在关联用户
			else {
				userEntity.setHeadIcon(wxUserEntity.getAvatarUrl());
				userEntity.setUserName(wxUserEntity.getNickName());

				//异步更新用户和微信用户表
				new Thread(new Runnable() {
					public void run() {
						try {
							updateUser(userEntity);
						} catch (Exception e) {
						}
						try {
							wxUserMapper.updateWxUserEntity(wxUserEntity);
						} catch (Exception e) {
						}
					}
				}).start();
				
				return userEntity;
			}


		}
	}






	@Override
	public boolean userExist(Long userId) {
		return userMapper.userExist(userId);
	}
	@Override
	public boolean userInCircle(Long userId,Long circleId) {
		return userMapper.userInCircle(userId, circleId);
	}
	@Override
	public boolean userInTask(Long userId,Long taskId) {
		return userMapper.userInTask(userId, taskId);
	}

	@Override
	public int updateSmallFromIdState(Long userId, String fromId, Integer state) {
		return userMapper.updateSmallFromIdState(userId,fromId,state);
	}

	@Override
	public int addSmallFromId(Long userId, String fromId) {

		if(!userMapper.existFromId(userId,fromId)) {
			return userMapper.addSmallFromId(userId,fromId);
		}
		return 1 ;
	}

	@Override
	public String getFromId(Long userId) {
		return userMapper.getFromId(userId);
	}

	@Override
	public Long getUnreadCount(Long userId) {
		return userMapper.getUnreadCount(userId);
	}

	/**
	 * 更新用户的登录时间
	 * @param userId 用户ID
	 */
	@Override
	public Long updateLoginTime(Long userId) {
		return userMapper.updateLoginTime(userId) ;
	}

	/**
	 * 获取用户的最后的登录时间
	 * @param userId 用户ID
	 */
	@Override
	public Date getLoginTime(Long userId) {
		return userMapper.getLoginTime(userId) ;
	}
}
